﻿// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;

namespace TheOliver.Controls
{
    public partial class ClipClapCountdown : UserControl
    {
        public ClipClapCountdown()
        {
            InitializeComponent();
            
            this.Loaded += new RoutedEventHandler(ClipClapCountdown_Loaded);
        }

        DispatcherTimer _timer;

        void ClipClapCountdown_Loaded(object sender, RoutedEventArgs e)
        {
            RestartTimer();
        }

        private void RestartTimer()
        {
            _timer = new DispatcherTimer();
            _timer.Tick += timer_Tick;
            _timer.Interval = new TimeSpan(0, 0, 1);
            _timer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            UpdateDisplay();
        }

        private void UpdateDisplay()
        {
            DateTime now = DateTime.Now;
            TimeSpan ts = _finaleTime.Subtract(now);
            if (ts.Ticks < 0)
            {
                _timer.Stop();
                ts = new TimeSpan(0, 0, 0);
            }

            _days.Text = ts.Days.ToString("00");
            _hours.Text = ts.Hours.ToString("00");
            _minutes.Text = ts.Minutes.ToString("00");
            _seconds.Text = ts.Seconds.ToString("00");
            
        }

        private DateTime _finaleTime = new DateTime(2020, 12, 24);
        public DateTime FinaleTime
        {
            get { return _finaleTime; }
            set { _finaleTime = value; RestartTimer(); }
        }

    }
}